import { action, observable } from 'mobx';
import { queryUserCfg } from '../service';
import { getCfgValue, getCfgList } from '../../components/Cfg/LayoutCfg';

class AppStore {
  // 用户配置信息
  @observable userInfo = {
    cfgs: [],
    moduleTree: [],
    user: {},
  };

  moduleList = [];

  @observable leftMenuTree = {
    rootSubmenuKeys: [],
    openKeys: [],
  };

  @observable passwordDialog = {
    visible: false,
    loading: false,
  };

  // 当前url
  @observable currentUrl = './background.html';

  getMenuItem(key) {
    for (let item of this.moduleList) {
      if (item.id == key) {
        return item;
      }
    }
  }

  constructor() {
    this.initUserCfg();
  }

  getCfgValue(key) {
    return getCfgValue(this.userInfo.cfgs, key);
  }

  @action
  async initUserCfg() {
    let res = await queryUserCfg();
    if (res.code != 0) {
      window.location.href = './login.html';
      return;
    }
    this.userInfo = res.data;
    // 缓存功能菜单列表
    this.initModuleList();
    document.title = getCfgValue(this.userInfo.cfgs, 'application.title');
    window.changeUserCfg = this.changeUserCfg;
  }

  initModuleList() {
    let loop = data => {
      data.map(item => {
        this.moduleList.push(item);
        // 优先加载本次回话最后打开的页面
        if (sessionStorage.getItem('url') != null) {
          this.currentUrl = sessionStorage.getItem('url');
        }else {
          // 如果是自启动菜单，则启动
          if (item.isAutorun) {
            this.changeUrl(item.id);
          }
        }
        if (item.children != null) {
          loop(item.children);
        }
      });
    };
    loop(this.userInfo.moduleTree);
  }

  @action
  changeUserCfg(cfg) {
    window.location.href = './main.html';
  }

  @action changeUrl(key) {
    let clickItem = this.getMenuItem(key);
    if (clickItem.url != null && clickItem.url != '') {
      this.redirectUrl(clickItem.url);
    }

    return clickItem;
  }

  @action redirectUrl(url) {
    this.currentUrl = url + (url.indexOf('?') == -1 ? '?' : '&') + Math.random();
    sessionStorage.setItem('url', this.currentUrl);
  }

  @action
  showChangePwdDialog(visible) {
    this.passwordDialog.visible = visible == null ? true : visible;
  }

  @action
  leftMenuOpenChange(openKeys) {
    const latestOpenKey = openKeys.find(key => this.leftMenuTree.openKeys.indexOf(key) === -1);
    if (this.leftMenuTree.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.leftMenuTree.openKeys = openKeys;
    } else {
      this.leftMenuTree.openKeys = latestOpenKey ? [latestOpenKey] : [];
    }
  }
}


export default AppStore;
